package com.migu.rbac.controller;

import com.migu.rbac.model.SysBackApi;
import com.migu.rbac.service.SysBackApiService;
import com.migu.rbac.vo.GlobalConst;
import com.migu.rbac.vo.Response;
import com.migu.rbac.vo.page.ApiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Description TODO : url
 * @Author: zj
 * @Date: 11:16 2019/4/8
 * @Version 1.0
 **/
@RestController
@RequestMapping(path = "/api/v1/url")
public class BackApiController {
    @Autowired
    SysBackApiService apiService;

    //分页查询url信息
    @PostMapping("/url-page")
    public Response urlPage(@RequestBody ApiPage page) {
        Response result = null;
        try {
            result = Response.success(apiService.selectApiByExample(page));
        } catch (Exception e) {
            result = Response.error(GlobalConst.Code.FAIL_500, e.getMessage());
        }
        return result;
    }

    //添加url
    @PostMapping("/saveUrl")
    public Response saveUrl(@RequestBody SysBackApi api) {
        Response result = null;
        try {
            if (apiService.save(api)) {
                result = Response.success(true);
            } else {
                result = Response.error(GlobalConst.Code.ERROR_400, "url已经存在或添加失,请联系管理员！");
            }
        } catch (Exception e) {
            result = Response.error(GlobalConst.Code.FAIL_500, e.getMessage());
        }
        return result;
    }

    //删除url
    @DeleteMapping("/deleteUrl/{id}")
    public Response deleteUrl(@PathVariable int id) {
        Response result = null;
        try {
            if (apiService.deleteUrl(id)) {
                result = Response.success(true);
            } else {
                result = Response.error(GlobalConst.Code.ERROR_400, "删除失败，请联系管理员 ！");
            }
        } catch (Exception e) {
            result = Response.error(GlobalConst.Code.FAIL_500, e.getMessage());
        }
        return result;

    }

    //查询所有url
    @GetMapping("/getUrl")
    public Response getUrl() {
        Response result = null;
        try {
            result = Response.success(apiService.findAllApi());
        } catch (Exception e) {
            result = Response.error(GlobalConst.Code.FAIL_500, e.getMessage());
        }
        return result;
    }

    //修改url
    @PutMapping("/updateUrl")
    public Response updateUrl(@RequestBody SysBackApi api) {
        Response result = null;
        try {
            if (apiService.updateUrlById(api)) {
                result = Response.success();
            } else {
                result = Response.error(GlobalConst.Code.ERROR_400, "修改失败，请联系管理员 ！");
            }
        } catch (Exception e) {
            result = Response.error(GlobalConst.Code.FAIL_500, e.getMessage());
        }
        return result;
    }
}
